import 'package:get/get.dart';
import 'package:interview/controller/user_controller.dart';
import 'package:interview/utils/http.dart';
import 'package:interview/utils/logger.dart';


/// LoginParams 请求参数封装
class LoginParams {
  final String username;
  final String password;


  LoginParams({
    required this.username,
    required this.password,

  });

  /// 转换为请求参数的 Map
  Map<String, dynamic> toJson() {
    return {
      'username': username,
      'password': password,
    };
  }
}


class User {
  final String id;
  final String username;
  final String avatar;
  final String token;
  final String? nickName;
  final int totalTime;
  final int clockinNumbers;

  User({
    required this.id,
    required this.username,
    required this.avatar,
    required this.token,
    required this.totalTime,
    required this.clockinNumbers,
    this.nickName
  });


  factory User.fromJson(Map<String , dynamic> json){
    return User(
      id:json["id"],
      username: json["username"],
      avatar: json["avatar"],
      token: json["token"],
      totalTime: json["totalTime"],
      clockinNumbers: json["clockinNumbers"],
      nickName: json["nickName"]
    );
  }

    // 将 User 转换为 Map
  Map<String, dynamic> toJson() => {
    'id': id,
    'username': username,
    'avatar': avatar,
    'token': token,
    'totalTime': totalTime,
    'clockinNumbers': clockinNumbers,
  };
}

Future<bool> fetchLogin(LoginParams params) async {
  try {
    final response = await Http.post('login' , data: params.toJson());
    // 检查响应结构
    if (response['success'] == true && response['data'] is Map<String, dynamic>) {
      final data = response['data'] as Map<String, dynamic>;
      final user = User(
        id: data["id"],
        username: data["username"],
        avatar: data["avatar"],
        token: data["token"],
        totalTime: data["totalTime"],
        clockinNumbers: data["clockinNumbers"],
      );

      // 获取 UserController 实例并调用 saveUser 方法
      final userController = Get.find<UserController>();
      await userController.saveUser(user);  // 保存用户信息
      
      return true;
    } else {
      Logger.error('响应数据格式错误或未成功: ${response['message']}' , tag: "fetchLogin");
      return false;  // 登录失败，返回 false
    }
  } catch (e , stackTrace) {
    Logger.error("登录失败: $e", tag: 'fetchQuestionList' , stackTrace: stackTrace);
    throw Exception('登录失败: $e');
    
  }
}